package com.mytime.resources;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.CharacterSet;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.mytime.database.Event;
import com.mytime.database.PMF;
import com.mytime.database.Timetable;
import com.mytime.database.Venue;

public class EventsByRegion extends ServerResource {
	
	private String cityId;
	
	@Override
	public void doInit() {
		this.cityId = (String) getRequestAttributes().get("city_id");
	}

	/**
     * Handles a GET HTTP request.
     * Returns all events from a given Venue. 
     * @param entity
	 * @throws JSONException 
     */
	@Get
	public Representation getEvents() throws JSONException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		JSONObject venuesObject = new JSONObject();
		JSONArray eventsArray = new JSONArray();
		
		//Get Events from a region in the city
		Query cityEvents = pm.newQuery(Venue.class);
		String filter = "cityId == " + cityId;
		cityEvents.setFilter(filter);
		
		@SuppressWarnings("unchecked")
		List<Venue> venuesList = (List<Venue>) cityEvents.execute();
	
		//TODO: Tentar melhorar essa consulta!!!
		for (Venue v: venuesList) {
			venuesObject.put(v.getStrKey(), new JSONArray());
			
			//Get Events
			HashSet<Key> events = (HashSet<Key>) v.getEventsList();
			Iterator<Key> itr = events.iterator();
			
			while(itr.hasNext()) {
				Key eventKey = itr.next();
				JSONObject eventObj = new JSONObject();
				JSONArray eventShowtimes = new JSONArray();
				Event e = (Event) pm.getObjectById(Event.class, eventKey);
				
				if (e == null)
					continue;
				
				eventObj = e.toJSON();
				
				//Get showtimes
				Query eventShowtimesQuery = pm.newQuery(Timetable.class);
				filter = "eventId == \'" + KeyFactory.keyToString(e.getKey()) + "\'";
	    		filter += " && venueId == \'" + KeyFactory.keyToString(v.getKey()) + "\'";
				eventShowtimesQuery.setFilter(filter);
				
				@SuppressWarnings("unchecked")
				List<Timetable> timeResults = (List<Timetable>) eventShowtimesQuery.execute();  
				
				for (Timetable t: timeResults) {
					eventShowtimes.put(t.toJSON());
				}
				
				eventObj.put("showtimes", eventShowtimes);
				eventsArray.put(eventObj);
				venuesObject.getJSONArray(v.getStrKey()).put(eventObj);
			}
			
			
			
		}
		
		return getRepresentation(venuesObject); 
	}
	
	/**
	 * Returns the JSON representation for a given JSON object.
	 * */
    private Representation getRepresentation(JSONObject jsonObject) {
    	JsonRepresentation jr = new JsonRepresentation(jsonObject);
    	jr.setCharacterSet(CharacterSet.UTF_8);
    	
    	return jr;
    }    
	
}
